package com.hw.core.system.controller;

import com.hw.core.system.entity.Permission;
import com.hw.core.system.entity.Role;
import com.hw.core.system.service.PermissionService;
import com.hw.core.system.service.RoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
@RequestMapping("role")
public class RoleController {
    private static final Logger logger = LoggerFactory.getLogger( RoleController.class );


    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;


    @GetMapping("list")
    @RequiresPermissions(value = "角色查询")
    public String list(Model model) {
        model.addAttribute( "roles", roleService.findAll() );
        return "role/listRole";
    }

    @GetMapping("edit")
    @RequiresPermissions(value = "角色修改")
    public String edit(Integer id, Model model) {
        Role role = roleService.getRoleById( id );
        List<Permission> permissionsNotInRoleId = permissionService.findPermissionsNotInRoleId( id );
        model.addAttribute( "role", role );
        model.addAttribute( "permissions", permissionsNotInRoleId );
        return "role/editRole";

    }

    @PostMapping("edit")
    @RequiresPermissions(value = "角色修改")
    @ResponseBody
    public String edit(Role role, Integer[] ids) {
        List<Permission> permissions = new ArrayList<>();
        if (ids != null) {
            for (Integer id : ids) {
                permissions.add( new Permission( id ) );
            }
        }
        role.setPermissions( permissions );
        roleService.update( role );
        return "修改成功";
    }

    @PostMapping("add")
    @ResponseBody
    @RequiresPermissions(value = "角色新增")
    public String add(String name, Integer[] ids) {
        Role role = new Role( name );
        ArrayList<Permission> permissions = new ArrayList<>();
        if (ids != null)
            for (Integer id : ids) {
                permissions.add( new Permission( id ) );
            }
        role.setPermissions( permissions );
        if (roleService.add( role ) != null) {
            return "添加成功";
        }
        return "添加失败";
    }

    @GetMapping("add")
    @RequiresPermissions(value = "角色新增")
    public String add(Model model) {
        List<Permission> permissions = permissionService.findAll();
        model.addAttribute( "permissions", permissions );
        return "role/addRole";
    }


    @PostMapping("delete")
    @RequiresPermissions(value = "角色删除")
    @ResponseBody
    public String delete(Integer id) {
        roleService.delete( id );
        return "删除成功";

    }


}
